package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;


    public List<Menu> selectRooMenu() {
        return menuMapper.selectParentMenus();
    }

    public List<Long> selectMenuByRoleId(Long id) {
        return menuMapper.selectMenuByRoleId(id);
    }


    public List<Menu> selectMenuByEmpId() {
        /*获取所有父菜单*/
        List<Menu> menus = menuMapper.selectParentMenus();
        /*获取当前用户*/
        Employee currentUser = UserContext.getCurrentUser();
        /*不是超管就查询用户所拥有的菜单*/
        if (!currentUser.getAdmin()) {
            /*查询用户所拥有的菜单的id集合*/
            List<Long> menuIds = menuMapper.selectByEmpId(currentUser.getId());
            /*如果用户存在菜单id,就选取对应的菜单*/
            if (menuIds != null) {
                /*去选取对应的菜单*/
                selectCheckMenuPermission(menus,menuIds);
            }

        }
        /*最后过滤后的菜单,都是用户所拥有的菜单*/
        return menus;
    }

    private void selectCheckMenuPermission(List<Menu> menus,List<Long> menuIds){
        /*迭代所有父菜单*/
        Iterator<Menu> iterator = menus.iterator();
        while(iterator.hasNext()){
            Menu menu = iterator.next();
            /*如果父菜单有不在用户菜单id集合中的,就删除*/
            if(!menuIds.contains(menu.getId())){
                iterator.remove();
                /*并跳到下一个父菜单的判断*/
                continue;
            }
            /*父菜单有在用户菜单中,则判断这个父菜单是否存在子菜单*/
            if(menu.getChildren().size()>0){
                /*有子菜单就递归子菜单*/
                selectCheckMenuPermission(menu.getChildren(),menuIds);
            }
        }
    }
}
